<?php

namespace App\Http\Controllers\System;

use App\Http\Controllers\Controller;
use App\Http\Requests\System\Attachment\StoreRequest;
use App\Http\Resources\System\Attachment\IndexResource;
use App\Http\Resources\System\Attachment\InfoResource;
use App\Models\System\Admin;
use App\Models\System\Attachment;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Spatie\QueryBuilder\QueryBuilder;

class AttachmentController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $list = QueryBuilder::for(Attachment::class, $request)
            ->allowedFilters(['id', 'admin_id', 'user_id', 'url', 'url_md5', 'mimetype', 'filesize'])
            ->allowedSorts('id')
            ->paginate();

        return $this->success(IndexResource::collection($list));
    }

    public function show(Attachment $attachment): JsonResponse
    {
        return $this->success(new InfoResource($attachment));
    }

    public function store(StoreRequest $request): JsonResponse
    {
        $file = $request->file('file');
        if (! $file->isValid()) {
            return $this->error('文件上传失败');
        }
        $sha1Hash = sha1_file($file->getRealPath());

        if (Attachment::query()->where('sha1', $sha1Hash)->first()) {
            return $this->error('文件重复');
        }

        $path = $file->store('images', 'public');
        if (! $path) {
            return $this->error('文件上传失败');
        }

        /** @var Admin $admin */
        $admin = $request->user();
        $row = new Attachment([
            'admin_id' => $admin->id,
            'filename' => $file->getClientOriginalName(),
            'url' => $path,
            'url_md5' => md5($path),
            'fileinfo' => '',
            'mimetype' => $file->getMimeType(),
            'filesize' => $file->getSize(),
            'sha1' => $sha1Hash,
        ]);
        $row->save();

        return $this->success([
            'id' => $row->id,
            'filename' => $row->filename,
            'url' => $row->url,
        ], 'store success');
    }

    public function destroy(Attachment $attachment): JsonResponse
    {
        $attachment->delete();

        return $this->success([], 'delete success');
    }
}
